package com.mlink.vs.action;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.upload.FormFile;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;
import org.seasar.struts.util.UploadUtil;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mlink.vs.entity.PiccTaskAudio;
import com.mlink.vs.entity.PiccTaskFile;
import com.mlink.vs.entity.PiccTaskPool;
import com.mlink.vs.entity.PiccTaskStatus;
import com.mlink.vs.entity.PiccUser;
import com.mlink.vs.form.ScreenUploadForm;
import com.mlink.vs.service.DbTimeService;
import com.mlink.vs.service.PiccTaskAudioService;
import com.mlink.vs.service.PiccTaskFileService;
import com.mlink.vs.service.PiccTaskPoolService;
import com.mlink.vs.service.PiccTaskStatusService;
import com.mlink.vs.service.PiccUserService;
import com.mlink.vs.util.Constants;

/**
 * 文件上传接口
 * @author Administrator
 */
public class UploadAction {
	
	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;
	
	@ActionForm
	@Resource
	protected ScreenUploadForm screenUploadForm;
	
	@Resource
	PiccTaskPoolService piccTaskPoolService;
	
	@Resource
	PiccTaskFileService piccTaskFileService;
	
	@Resource
	PiccTaskStatusService piccTaskStatusService;
	
	@Resource
	PiccUserService piccUserService;
	@Resource
	
	PiccTaskAudioService piccTaskAudioService;

	@Resource
	DbTimeService dbTimeService;
	
	/**
	 * 图片案件
	 * @return
	 */
	@Execute(validator = false)
	public String index(){
		Gson gson = new Gson();
		Map<String, String> stsMap = new HashMap<String, String>();
		
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("PHOTO_STORE_PATH");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[PHOTO_STORE_PATH]未配置，异常退出");
			return null;
		}

		// 获取提交的截屏信息
		String caseNumber = screenUploadForm.getCaseNumber();
		String carNumber = screenUploadForm.getCarNumber();
		String caseType = screenUploadForm.getCaseType();
		String userId = screenUploadForm.getUserId();
		String lon = screenUploadForm.getLon();
		String lat = screenUploadForm.getLat();
		String address = screenUploadForm.getAddress();
		String describe = screenUploadForm.getDescribe();
		FormFile file = screenUploadForm.getFiledatastream();
		
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(carNumber)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "carNumber不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(caseNumber)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "caseNumber不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
	
			//查看这个报案号和车牌号是否上传过录音文件
			PiccTaskAudio piccTaskAudio= piccTaskAudioService.findTask(caseNumber,carNumber);
			String taskId=null;
			if(piccTaskAudio==null){
				taskId=UUID.randomUUID().toString().replace("-", "");
			}else{
				taskId=piccTaskAudio.taskId;
			}
			
			// 存取在当天目录
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			String datePath = df.format(new Date());
			File saveDir = new File(scFileSavePath + File.separator + datePath);
			if (!saveDir.exists()) {
				saveDir.mkdirs();
			}
			UploadUtil.write(saveDir + File.separator + file.getFileName(),file);
	
			PiccTaskPool piccTaskPool = piccTaskPoolService.findTask(caseNumber,carNumber);
			if(null!=piccTaskPool){
				//已有任务
				Timestamp dbTimeStamp = dbTimeService.getDbTimeStamp();
				//直接往任务文件表添加数据
				PiccTaskFile piccTaskFile = new PiccTaskFile(); 
				piccTaskFile.fileId=UUID.randomUUID().toString().replace("-", "");
				piccTaskFile.taskId=piccTaskPool.taskId;;
				piccTaskFile.caseNumber=caseNumber;
				piccTaskFile.carNumber=carNumber;
				PiccUser piccUser = piccUserService.findById(userId);
				piccTaskFile.createUser=piccUser.userName;
				piccTaskFile.fileUrl=datePath + File.separator + file.getFileName();
				piccTaskFile.createTime=dbTimeStamp;
				piccTaskFileService.insert(piccTaskFile);
				
				//修改任务表任务修改时间
					//如果之前是视频定损类型，就改为图片定损类型，往历史表里添加数；否则不做处理
					if(Constants.TASK_TYPE_VIDEO.equals(piccTaskPool.taskType)){
						PiccTaskStatus piccTaskStatus = new PiccTaskStatus();
						piccTaskStatus.id=UUID.randomUUID().toString().replace("-", "");
						piccTaskStatus.taskId=piccTaskPool.taskId;
						piccTaskStatus.taskStatus=Constants.TASK_STATUS_DAICL;
						piccTaskStatus.taskType=Constants.TASK_TYPE_PICTURE;
						piccTaskStatus.createTime=dbTimeStamp;
						piccTaskStatusService.insert(piccTaskStatus);
						
						piccTaskPool.taskType=Constants.TASK_TYPE_PICTURE;
						piccTaskPool.dsNumber=piccTaskPool.dsNumber+1;
					}else{
						List<PiccTaskFile> piccTaskFileList = piccTaskFileService.findByTaskId(piccTaskPool.taskId);
						PiccTaskFile piccTaskFile2 = piccTaskFileList.get(1);
						Timestamp createTime2 = piccTaskFile2.createTime;
						
						SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String format2 = dfs.format(createTime2);
						String format1 = dfs.format(dbTimeStamp);
						Date formatt2=dfs.parse(format2);
						Date formatt1 = dfs.parse(format1);
						long min=(formatt1.getTime()-formatt2.getTime())/1000/60;
						//此次定损时间距上次定损时间超过10分钟,定损次数+1
						if(min>=Long.valueOf(Constants.A_SET_TIME)){
							piccTaskPool.dsNumber=piccTaskPool.dsNumber+1;
						}
					}	
				piccTaskPool.updateTime=dbTimeStamp;
				piccTaskPoolService.update(piccTaskPool);
				
				stsMap.put("sts", "0");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}else{
				PiccUser piccUser = piccUserService.findById(userId);
				String groupName=piccUser.groupName;
				//没有任务，先新建任务
				PiccTaskPool piccTaskPool2 = new PiccTaskPool();
				piccTaskPool2.taskId=taskId;
				piccTaskPool2.leadingUserId=userId;
				piccTaskPool2.caseNumber=caseNumber;
				piccTaskPool2.carNumber=carNumber;
				piccTaskPool2.caseType=caseType;
				piccTaskPool2.taskType=Constants.TASK_TYPE_PICTURE;
				piccTaskPool2.lon=lon;
				piccTaskPool2.lat=lat;
				piccTaskPool2.address=address;
				piccTaskPool2.taskDescribe=describe;
				piccTaskPool2.groupName=groupName;
				Timestamp dbTimeStamp = dbTimeService.getDbTimeStamp();
				piccTaskPool2.createTime=dbTimeStamp;
				piccTaskPool2.updateTime=dbTimeStamp;
				piccTaskPool2.firstNumber=Integer.valueOf(Constants.TASK_DEFAULT_NUMBER);
				piccTaskPool2.dsNumber=Integer.valueOf(Constants.TASK_DS_NUMBER);
				piccTaskPool2.deleteFlag=false;
				String isOnline=Constants.USER_STATUS_ONLINE;
				String userType1=Constants.USER_TYPE_SEAT;
				String userType2=Constants.USER_TYPE_LEADER;
				List<PiccUser> findZuoXi = piccUserService.findZuoXi(groupName,isOnline,userType1,userType2);
				String taskStatus=Constants.TASK_STATUS_WAIT_APP;
				if(null!=findZuoXi&&findZuoXi.size()>0){
					//查询 哪个在线坐席正在处理的案件量最少 把此案件分配给他
					String taskType = Constants.TASK_TYPE_PICTURE;
					List<Map> findPictureTask = piccTaskPoolService.findPictureTask(userId,userType1,userType2,taskStatus,taskType,isOnline);
					Map<String , Object> mapp = findPictureTask.get(0);
					String idd = (String) mapp.get("f1");
					piccTaskPool2.sertId=idd;
				}else{
					List<PiccUser> findLeder = piccUserService.findLeader(groupName,userType2);
					if(null!=findLeder && findLeder.size()>0){
						String userId2 = findLeder.get(0).userId;
						piccTaskPool2.sertId=userId2;
					}else{
						stsMap.put("sts", "5");
						stsMap.put("msg", "该组没有组长");
						rep.getWriter().println(gson.toJson(stsMap));
						rep.getWriter().flush();
					}
				}
				piccTaskPool2.taskStatus=taskStatus;
				piccTaskPoolService.insert(piccTaskPool2);
				
				//往任务图片文件表里添加
				PiccTaskFile piccTaskFile = new PiccTaskFile(); 
				piccTaskFile.fileId=UUID.randomUUID().toString().replace("-", "");
				piccTaskFile.taskId=piccTaskPool2.taskId;;
				piccTaskFile.caseNumber=caseNumber;
				piccTaskFile.carNumber=carNumber;
				piccTaskFile.createUser=piccUser.userName;
				piccTaskFile.fileUrl=datePath + File.separator + file.getFileName();
				piccTaskFile.createTime=dbTimeStamp;
				piccTaskFileService.insert(piccTaskFile);
				
				//往任务历史表里添加
				PiccTaskStatus piccTaskStatus = new PiccTaskStatus();
				piccTaskStatus.id=UUID.randomUUID().toString().replace("-", "");
				piccTaskStatus.taskId=piccTaskPool2.taskId;
				piccTaskStatus.taskStatus=Constants.TASK_STATUS_WAIT_APP;
				piccTaskStatus.taskType=Constants.TASK_TYPE_PICTURE;
				piccTaskStatus.createTime=dbTimeStamp;
				piccTaskStatusService.insert(piccTaskStatus);
				stsMap.put("sts", "0");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
		}
			
			}catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		

		return null;
	}
	
	/**
	 * 视频中的截图
	 * @return
	 */
	@Execute(validator = false)
	public String VideoPicture(){
		Gson gson = new Gson();
		Map<String, String> stsMap = new HashMap<String, String>();
		
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("PHOTO_STORE_PATH");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[PHOTO_STORE_PATH]未配置，异常退出");
			return null;
		}
		
		final String scFileSavePathh = context.getInitParameter("SERVER_URL_FOR_IMAGE");

		if (scFileSavePathh == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SERVER_URL_FOR_IMAGE]未配置，异常退出");
			return null;
		}

		// 获取提交的截屏信息
		String taskId = screenUploadForm.getTaskId();
		FormFile file = screenUploadForm.getFiledatastream();
		
		
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(taskId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "taskId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
	
			PiccTaskPool piccTaskPool = piccTaskPoolService.findById(taskId);
			if(null!=piccTaskPool){
				//已有任务
				// 存取在当天目录
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
				String datePath = df.format(new Date());
				File saveDir = new File(scFileSavePath + File.separator + datePath);
				if (!saveDir.exists()) {
					saveDir.mkdirs();
				}
				UploadUtil.write(saveDir + File.separator + file.getFileName(),file);
			
				//修改任务表任务修改时间
				Timestamp dbTimeStamp = dbTimeService.getDbTimeStamp();
				piccTaskPool.updateTime=dbTimeStamp;
				piccTaskPoolService.update(piccTaskPool);
				//往任务图片文件表添加数据
				PiccTaskFile piccTaskFile = new PiccTaskFile(); 
				piccTaskFile.fileId=UUID.randomUUID().toString().replace("-", "");
				piccTaskFile.taskId=piccTaskPool.taskId;
				piccTaskFile.caseNumber=piccTaskPool.caseNumber;
				piccTaskFile.carNumber=piccTaskPool.carNumber;
				PiccUser piccUser = piccUserService.findById(piccTaskPool.leadingUserId);
				piccTaskFile.createUser=piccUser.userName;
				piccTaskFile.fileUrl=datePath + File.separator + file.getFileName();
				piccTaskFile.createTime=dbTimeStamp;
				piccTaskFileService.insert(piccTaskFile);
				String fileUrl = piccTaskFile.fileUrl;
				String replace = fileUrl.replace("\\", "%2f").replace("/", "%2f");
				String s = scFileSavePathh + replace;
				stsMap.put("sts", "0");
				stsMap.put("imgUrl", s);
				GsonBuilder gb =new GsonBuilder();
				gb.disableHtmlEscaping();
				String aa = gb.create().toJson(stsMap);
				rep.getWriter().println(aa);
				rep.getWriter().flush();
			}else{
				stsMap.put("sts", "2");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}
			
			}catch (IOException e) {
				e.printStackTrace();
			}
		

		return null;
	}
	
	/**
	 * 聊天中的图片
	 * @return
	 */
	@Execute(validator = false)
	public String ChatPicture(){
		Map<String, String> stsMap = new HashMap<String, String>();
		
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("PHOTO_STORE_PATH");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[PHOTO_STORE_PATH]未配置，异常退出");
			return null;
		}
		
		final String scFileSavePathh = context.getInitParameter("SERVER_URL_FOR_IMAGE");

		if (scFileSavePathh == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SERVER_URL_FOR_IMAGE]未配置，异常退出");
			return null;
		}

		// 获取提交的截屏信息
		FormFile file = screenUploadForm.getFiledatastream();
		
		try {
			rep.setCharacterEncoding("utf-8");
	
			// 存取在当天目录
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
			String datePath = df.format(new Date());
			File saveDir = new File(scFileSavePath + File.separator + datePath);
			if (!saveDir.exists()) {
				saveDir.mkdirs();
			}
			UploadUtil.write(saveDir + File.separator + file.getFileName(),file);
	
			//往任务图片文件表添加数据
			PiccTaskFile piccTaskFile = new PiccTaskFile(); 
			piccTaskFile.fileId=UUID.randomUUID().toString().replace("-", "");
			piccTaskFile.taskId=Constants.CHAT_PICTURE_TASKID;
			piccTaskFile.caseNumber=Constants.CHAT_PICTURE_CASE_NUMBER;
			piccTaskFile.carNumber=Constants.CHAT_PICTURE_CAR_NUMBER;
			piccTaskFile.createUser=Constants.CHAT_PICTURE_CAR_NUMBER;
			piccTaskFile.fileUrl=datePath + File.separator + file.getFileName();
			piccTaskFile.createTime=dbTimeService.getDbTimeStamp();
			piccTaskFileService.insert(piccTaskFile);
			
			String fileUrl = piccTaskFile.fileUrl;
			String replace = fileUrl.replace("\\", "%2f").replace("/", "%2f");
			String s = scFileSavePathh + replace;
			stsMap.put("sts", "0");
			stsMap.put("imgUrl", s);
			
			GsonBuilder gb =new GsonBuilder();
			gb.disableHtmlEscaping();
			String aa = gb.create().toJson(stsMap);
			rep.getWriter().println(aa);
			rep.getWriter().flush();
			
			}catch (IOException e) {
				e.printStackTrace();
			}
		
		return null;
	}
	
	/**
	 * 案件定损中的录音
	 * @return
	 */
	@Execute(validator = false)
	public String taskAudio(){
		Gson gson = new Gson();
		Map<String, String> stsMap = new HashMap<String, String>();
		
		ServletContext context = req.getSession().getServletContext();
		final String scFileSavePath = context
				.getInitParameter("SOUND_STORE_PATH");

		if (scFileSavePath == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SOUND_STORE_PATH]未配置，异常退出");
			return null;
		}
		
		final String scFileSavePathh = context.getInitParameter("SERVER_URL_FOR_SOUND");

		if (scFileSavePathh == null) {
			// 环境变量未配置，异常退出
			System.out.println("环境变量[SERVER_URL_FOR_SOUND]未配置，异常退出");
			return null;
		}

		// 获取提交的音频信息
		String caseNumber = screenUploadForm.getCaseNumber();
		String carNumber = screenUploadForm.getCarNumber();
		FormFile file = screenUploadForm.getFiledatastream();
		String audioDesc = screenUploadForm.getAudioDesc();
		
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(caseNumber)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "caseNumber不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(carNumber)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "carNumber不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
	
			PiccTaskAudio piccTaskAudioo= piccTaskAudioService.findTask(caseNumber,carNumber);
			if(null==piccTaskAudioo){
				//没有任务
				// 存取在当天目录
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
				String datePath = df.format(new Date());
				File saveDir = new File(scFileSavePath + File.separator + datePath);
				if (!saveDir.exists()) {
					saveDir.mkdirs();
				}
				UploadUtil.write(saveDir + File.separator + file.getFileName(),file);
				//往任务音频文件表添加数据
				PiccTaskAudio piccTaskAudio = new PiccTaskAudio();
				piccTaskAudio.audioId=UUID.randomUUID().toString().replace("-", "");
				String randomUuid = UUID.randomUUID().toString().replace("-", "");
				piccTaskAudio.taskId=randomUuid;
				piccTaskAudio.caseNumber=caseNumber;
				piccTaskAudio.carNumber=carNumber;
				piccTaskAudio.audioName=randomUuid;
				piccTaskAudio.audioUrl=datePath + File.separator + file.getFileName();
				piccTaskAudio.audioDesc=audioDesc;
				piccTaskAudio.createTime=dbTimeService.getDbTimeStamp();
				piccTaskAudioService.insert(piccTaskAudio);
				String fileUrl = piccTaskAudio.audioUrl;
				String replace = fileUrl.replace("\\", "%2f").replace("/", "%2f");
				String s = scFileSavePathh + replace;
				stsMap.put("sts", "0");
				stsMap.put("audioUrl", s);
				GsonBuilder gb =new GsonBuilder();
				gb.disableHtmlEscaping();
				String aa = gb.create().toJson(stsMap);
				rep.getWriter().println(aa);
				rep.getWriter().flush();
			}else{
				stsMap.put("sts", "2");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}
			
			}catch (IOException e) {
				e.printStackTrace();
			}

		return null;
	}
	
}